import Header from '@/components/header';
import styles from "./index.module.scss";
import MenuBar from './components/menuBar';
import MainEdit from './components/MainEdit';
import Results from './components/Results';
import History from './components/History';
import { useState, useRef } from 'react';


export default function ImageEditPage() {
  const [currentMenuKey, setCurrentMenuKey] = useState('postProduction');
  const [currentMenuTitle, setCurrentMenuTitle] = useState('影视后期');
  const [showMainEdit, setShowMainEdit] = useState(true);
  const [showResults, setShowResults] = useState(true);
  const [showHistory, setShowHistory] = useState(true);
  
  const handleMenuClick = (item, confirmCallback) => {
    // 更新当前选中的菜单
    setCurrentMenuKey(item.key);
    setCurrentMenuTitle(item.title);
    // 更新组件显示状态
    setShowMainEdit(item.showMainEdit || false);
    setShowResults(item.showResults || false);
    setShowHistory(item.showHistory || false);
    // 调用回调更新菜单状态
    confirmCallback?.();
  };
  
  // 创建refs数组来引用每个resultsItem和results容器
  const resultsItemRefs = useRef([]);
  const resultsContainerRef = useRef(null);
  
  // 点击history图片时滚动到对应的resultsItem
  const handleHistoryImageClick = (index) => {
    if (resultsItemRefs.current[index] && resultsContainerRef.current) {
      const resultsContainer = resultsContainerRef.current;
      const targetItem = resultsItemRefs.current[index];
      
      // 计算目标元素相对于容器的位置
      const containerRect = resultsContainer.getBoundingClientRect();
      const targetRect = targetItem.getBoundingClientRect();
      const scrollTop = resultsContainer.scrollTop;
      
      // 计算需要滚动的距离
      const targetScrollTop = scrollTop + (targetRect.top - containerRect.top);
      
      // 平滑滚动到目标位置
      resultsContainer.scrollTo({
        top: targetScrollTop,
        behavior: 'smooth'
      });
    }
  };
  
  return (
    <div className={styles.imageEditPage} id='imageEditPage'>
      <Header showLogo={false} title="视频编辑工作台" />
      <div className={styles.mainSection}>
        <div className={styles.mainContent}>
          <MenuBar onMenuChange={handleMenuClick}/>
          {showMainEdit && (
            <MainEdit 
              currentMenuKey={currentMenuKey}
              currentMenuTitle={currentMenuTitle}
            />
          )}
          {showResults && (
            <Results
              currentMenuKey={currentMenuKey}
              currentMenuTitle={currentMenuTitle}
              ref={resultsContainerRef}
              resultsItemRefs={resultsItemRefs}
            />
          )}
          {showHistory && (
            <History onHistoryImageClick={handleHistoryImageClick} />
          )}
        </div>
      </div>
    </div>
  );
}
